package com.shop.cereshop.app.service.product.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.product.CereProductVisitMapper;
import com.shop.cereshop.app.page.product.ProductVisitListVO;
import com.shop.cereshop.app.param.product.QueryProductVisitDTO;
import com.shop.cereshop.app.service.product.CereProductVisitService;
import com.shop.cereshop.app.service.redis.LabelService;
import com.shop.cereshop.app.utils.BusinessUtils;
import com.shop.cereshop.commons.domain.calculate.Calculate;
import com.shop.cereshop.commons.domain.product.CereProductVisit;
import com.shop.cereshop.commons.enums.ShopTypeEnum;
import com.shop.cereshop.commons.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品访问记录表 Service 实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CereProductVisitServiceImpl extends ServiceImpl<CereProductVisitMapper, CereProductVisit> implements CereProductVisitService {

    private final LabelService labelService;

    @Override
    @Transactional
    public Boolean saveProductVisit(CereProductVisit visit) {
        // 同一用户、同一商品，只保存最新的记录
        LocalDateTime now = LocalDateTime.now();
        CereProductVisit productVisit = baseMapper.selectLastVisitByUserAndProduct(visit.getBuyerUserId(), visit.getProductId());
        if (productVisit != null) {
            productVisit.setVisitTime(now);
            baseMapper.updateById(productVisit);
        } else {
            visit.setId(null);
            visit.setVisitTime(now);
            baseMapper.insert(visit);
        }
        return true;
    }

    @Override
    public Result<PageInfo<ProductVisitListVO>> getProductVisitPage(QueryProductVisitDTO queryDTO) {
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());
        List<ProductVisitListVO> products = baseMapper.queryUserProductVisitList(queryDTO);
        if (CollUtil.isEmpty(products)) {
            log.info("未查询到用户访问商品记录，buyerUserId: {}", queryDTO.getBuyerUserId());
            return Result.success(new PageInfo<>());
        }

        processProductAndShopLabels(products, queryDTO.getCityCode(), null);
        return Result.success(new PageInfo<>(products));
    }

    @Override
    public void clearByUserId(Long buyerUserId) {
        baseMapper.deleteByUserId(buyerUserId);
    }

    @Override
    public void deleteProductVisit(Long buyerUserId, Long visitId) {
        baseMapper.deleteByUserIdAndVisitId(buyerUserId, visitId);
    }

    @Override
    public void batchDeleteProductVisit(Long buyerUserId, List<Long> visitIds) {
        baseMapper.deleteBatch(buyerUserId, visitIds);
    }

    /**
     * 处理商品和店铺标签
     *
     * @param products 商品列表
     * @param cityCode 参数里的cityCode
     * @param shopType 参数里的店铺类型
     */
    private void processProductAndShopLabels(List<ProductVisitListVO> products, String cityCode, Integer shopType) {
        List<Long> productIds = products.stream().map(ProductVisitListVO::getProductId).collect(Collectors.toList());
        Map<Long, Calculate> labelMap = labelService.getProductLabelMap(productIds);

        List<Long> shopIds = products.stream().map(ProductVisitListVO::getShopId).distinct().collect(Collectors.toList());
        Map<Long, Calculate> serviceLabelMap = labelService.getShopServiceLabelMap(shopIds);

        for (ProductVisitListVO product : products) {
            Calculate productCalculate = labelMap.get(product.getProductId());
            product.setProductLabels(BusinessUtils.getProductLabels(productCalculate));

            Calculate shopCalculate = serviceLabelMap.get(product.getShopId());
            product.setShopLabels(BusinessUtils.getShopServiceLabels(shopCalculate));


//            if (shopType == null || shopType == 0) {
//                // 没有传shopType或shopType=0，则根据城市码判断
//                ShopTypeEnum shopTypeEnum = ShopTypeEnum.getByTypeAndAdcode(product.getShopType(), product.getShopCityCode(), cityCode);
//                if (shopTypeEnum != null) {
//                    product.setShopType(shopTypeEnum.getCode());
//                }
//            } else {
//                // 参数传了shopType，根据指定类型查询sql得到的结果
//                product.setShopType(shopType);
//            }
            product.setShopType(product.getProductType());
        }
    }

    @Override
    public List<CereProductVisit> getUserVisitHistory(Long userId) {
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public Long getProductVisitCount(Long productId) {
        return baseMapper.countVisitByProductId(productId);
    }

    @Override
    public List<CereProductVisit> getUserProductVisits(Long userId, Long productId) {
        return baseMapper.selectByUserAndProduct(userId, productId);
    }

    @Override
    public List<Map<String, Object>> getHotProducts(Integer limit) {
        return baseMapper.selectHotProducts(limit);
    }

    @Override
    public List<CereProductVisit> getRecentUserVisits(Long userId, Integer limit) {
        return baseMapper.selectRecentVisitsByUser(userId, limit);
    }

    @Override
    public Integer cleanExpiredVisits(LocalDateTime expireTime) {
        return baseMapper.deleteByTimeBefore(expireTime);
    }

    @Override
    public Map<String, Object> getVisitStatistics(LocalDateTime startTime, LocalDateTime endTime) {
        Long totalVisits = baseMapper.countVisitByTimeRange(startTime, endTime);
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalVisits", totalVisits);
        statistics.put("startTime", startTime);
        statistics.put("endTime", endTime);
        return statistics;

    }



}
